<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\epay\library\Service;
use think\Exception;
use app\common\library\wxPay;

/**
 * 支付接口
 */
class Payment extends Api
{

   
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['pay', 'test1','notify','coures_notify'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    public function pay()
    {  
        try {
            // 发起支付
            $sn = $this->request->param('sn');
            $order_info = model("\app\admin\model\order\Order")->where('sn',$sn)->find();
            if(!$order_info){
                throw new Exception('订单不存在');
            }
            if($order_info->pay_status){
                throw new Exception('订单已支付');
            }
            //订单号
            $type = $order_info->type;
            if($type == 'course'){
                $info = model("\app\admin\model\course\Course")->get($order_info->course_id);
            }else{

            }
            $amount = $order_info->amount;
            if (!$amount || $amount < 0) {
                throw new Exception('订单金额必须大于0');
            }
            // 支付方式
            $pay_type = $this->request->param('pay_type');
            if (!$pay_type || !in_array($pay_type, ['alipay', 'wechat'])) {
                throw new Exception('支付方式不存在');
            }
            $method = $this->request->param('method');
            if(!$method){
                throw new Exception('支付场景错误');
            }
            //回调链接
            $notifyurl = $this->request->root(true) . '/index/pay/notify/paytype/' . $pay_type;
            $returnurl = $this->request->root(true) . '/index/pay/complete/paytype/' . $pay_type . '/out_trade_no/' .$sn;
            // 支付场景
            $response = Service::submitOrder($amount, $sn, $pay_type,$info->title, $notifyurl, $returnurl, $method);  
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }
        $this->success('成功',$response);  
    }

     /**
     * 回调
     */
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            $order = model("\app\admin\model\order\Order");
            $orderInfo = $order->where('sn',$out_trade_no)->find();
            if($orderInfo->pay_status !== 1){
                $updateData = [
                    'pay_status' => 1,
                    'createtime' => time(),
                    'pay_type' => $paytype,
                    'real_price' => 1,
                    'pay_no' => $data['transaction_id']
                ];
                $order->where('sn',$out_trade_no)->update($updateData);
                $inserts = collection(model("\app\admin\model\course\ClassroomCourse")
                    ->where('classroom_id',1)
                    ->field('course_id')
                    ->select())->toArray();
                foreach($inserts as $key=>$val){
                    $inserts[$key]['member_id'] = $orderInfo->user_id;
                    $inserts[$key]['role'] = 'student';
                    $inserts[$key]['createtime'] = time();
                }
                model("\app\admin\model\course\Member")->insertAll($inserts);
            }

        } catch (Exception $e) {
            echo $pay->error($e->getMessage());
        }
        echo $pay->success();
    }


    /**
     * 录播课、咨询支付回调
     */
    public function coures_notify(){

        $xml = file_get_contents('php://input'); //接受通知参数；
        # 将服务器返回的XML数据转化为数组
        $wxPay = new wxPay();
        $data = $wxPay->XmlToArray($xml);
        $dataSign = $data['sign'];
        # sign不参与签名算法, 必须重视签名校验, 防止被截获之后, 别人发送篡之后的参数给我们
        unset($data['sign']);

        # 生成签名
        $mch_id     = Config('wxpay.mch_id'); //商户ID
        $pay_key    = Config('wxpay.pay_key'); //商户密钥
        $appid      = Config('wxpay.appid'); //微信分配的小程序ID
        $nonce_str  = md5(uniqid(md5(microtime(true)),true)); //生成随机字符串,长度要求在32位以内
        $notify_url = Config('wxpay.notify_url');//异步接收微信支付结果通知的回调地址

        $params=[
            'appid'=>$data['appid'],
            'mch_id'=>$data['mch_id'],
            'nonce_str'=>$data['nonce_str'],
            'body'=>$data['attach'],
            'openid'=>$data['openid'],
            'out_trade_no'=>$data['out_trade_no'],
            'total_fee'=>$data['total_fee'],
            'spbill_create_ip'=>$_SERVER['SERVER_ADDR'],
            'notify_url'=>$data['notify_url'],
            'trade_type'=>$data['trade_type'],
        ];

        $sign = $wxPay->MakeSign($params, $pay_key);

        $wx_total_fee = $data['total_fee']; # 微信返回的支付金额, 单位分
        # 判断签名是否正确  判断支付状态
        if (($sign === $dataSign) && ($data['return_code'] == 'SUCCESS') && ($data['result_code'] == 'SUCCESS')) {

            $order_sn = explode("-",$data['out_trade_no']); # 订单号, 订单号保持唯一生成哦
            $frist = substr($data['out_trade_no'], 0, 1);

            //查询支付log记录
            $pay_log_id = $order_sn[1];
            $pay_log = db('pay_log')->where('id',$pay_log_id)->find();

            if(empty($pay_log['order_sn']) || ($pay_log['pay_status'] > 0)){
                exit;
            }

            #更新订单状态，自身逻辑
            if($frist == "C"){
                //录播课支付
                $course_order_info = db('course_order')->where('order_sn',$pay_log['order_sn'])->find();
                if(empty($course_order_info)){
                    exit;
                }

                //修改订单信息
                $p_order_amount = [];
                $p_order_amount['pay_status'] = 1;//支付状态已完成
                $p_order_amount['updatetime'] = time();//修改时间
                $p_order_amount['transportation'] = $data['transaction_id'];//第三方流水

                $upd = db('course_order')->where('order_sn', $pay_log['order_sn'])->update($p_order_amount);
                if($upd){
                    //用户开课 
                    $this->addStuCourse($course_order_info['course_id'], $course_order_info['user_id'],$course_order_info['id']);
                    //更新优惠券状态
                    if(!empty($course_order_info['coupon_id'])){
                        $this->updatecoupon($course_order_info['coupon_id'],$course_order_info['id'],'course'); 
                    }
                    //更新paylog
                    $new_pay_log = [];
                    $new_pay_log['pay_status'] = 1;
                    $new_pay_log['updatetime'] = time();//修改时间
                    db('pay_log')->where('id', $pay_log['id'])->update($new_pay_log);

                    echo 'SUCCESS';

                }else{
                    echo 'FAIL';
                }

            }else if($frist == "S"){
                //咨询服务支付
                $task_order_info = db('task_order')->where('order_sn',$pay_log['order_sn'])->find();
                if(empty($task_order_info)){
                    exit;
                }

                //修改订单信息
                $s_order_amount = [];
                $s_order_amount['pay_status'] = 1;//支付状态已完成
                $s_order_amount['updatetime'] = time();//修改时间
                $s_order_amount['transportation'] = $data['transaction_id'];//第三方流水

                $upd = db('task_order')->where('order_sn', $pay_log['order_sn'])->update($s_order_amount);
                if($upd){

                    //更新优惠券状态
                    if(!empty($task_order_info['coupon_id'])){
                        $this->updatecoupon($task_order_info['coupon_id'],$task_order_info['id'],'service'); 
                    }
                    //更新paylog
                    $new_pay_log = [];
                    $new_pay_log['pay_status'] = 1;
                    $new_pay_log['updatetime'] = time();//修改时间
                    db('pay_log')->where('id', $pay_log['id'])->update($new_pay_log);

                    echo 'SUCCESS';

                }else{
                    echo 'FAIL';
                }

            }
            
        }else{
            echo 'FAIL';
        }

    }


    /**
     * 更新优惠券状态
     * 
     */
    public function updatecoupon($coupon_id = 0, $order_id = 0, $type = ''){

        if(empty($coupon_id)){
            return false;
        }

        //修改信息
        $ret = db('coupon_list')->where('id', $coupon_id)->update(['type' => $type,'order_id' => $order_id,'use_time' => time(),'status' => 1]);

        if($ret){
            return true;
        }else{
            return false;
        }

    }


    /**
     * 给用户开课
     */
    public function addStuCourse($course_id = 0, $user_id = 0, $course_order_id = 0){

        if(empty($course_id) || empty($user_id) || empty($course_order_id)){
            return false;
        }

        $course = db('course_member')->where('course_id',$course_id)->where('user_id',$user_id)->find();
        if(!empty($course['id'])){
            return true;
        }

        $course_member = [];
        $course_member['course_id'] = $course_id;//课程ID
        $course_member['user_id'] = $user_id;//用户ID
        $course_member['course_order_id'] = $course_order_id;//订单ID
        $course_member['role'] = "student";//角色
        $course_member['createtime'] = time();//创建时间

        db('course_member')->insert($course_member);

        return true;
    }



}
